package com.yenlien.traceyun.usercenter.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.common.crypt.CryptUtil;
import com.yenlien.traceyun.common.utils.Regex;
import com.yenlien.traceyun.usercenter.bean.AppMenuTree;
import com.yenlien.traceyun.usercenter.dao.*;
import com.yenlien.traceyun.usercenter.entity.*;
import com.yenlien.traceyun.usercenter.exception.UserException;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.Transient;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-04
 * @description:
 **/

@Service
public class UserService {
    @Autowired
    private AppService appService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private AppDao appDao;

    @Autowired
    private CustomAppVersionDao customAppVersionDao;

    @Autowired
    private FileService fileService;
    @Autowired
    private ResourceService resourceService;

    @Autowired
    private CompanyCustomAppVersionDao companyCustomAppVersionDao;

    @Autowired
    private CompanyDao companyDao;

    public Page<User> findByList(final User user) {
        Pageable pageable = PageRequest.of(user.getPage(), user.getPageSize(), Sort.Direction.DESC, "createtime");
        return userDao.findAll(new Specification<User>() {
            private static final long serialVersionUID = 6759150428571384059L;

            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //构造查询条件
                List<Predicate> list_and = new ArrayList<>();
                List<Predicate> list_or = new ArrayList<>();
                list_and.add(cb.equal(root.get("userType"), User.UserType.COMMON));
                if (!StringUtils.isEmpty(user.getCompanyId())) {
                    list_and.add(cb.equal(root.get("companyId"), user.getCompanyId()));
                }
                if (!StringUtils.isEmpty(user.getDepartmentId())) {
                    List<String> ids = new ArrayList<>();
                    getDepartmentIds(user.getDepartmentId(), ids);
                    list_and.add(cb.in(root.get("departmentId")).value(ids));
                }
                Predicate[] predicate = new Predicate[list_and.size()];
                Predicate pre_and = cb.and(list_and.toArray(predicate));
                if (!StringUtils.isEmpty(user.getQuery())) {
                    list_or.add(cb.like(root.get("name"), "%" + user.getQuery() + "%"));
                    list_or.add(cb.like(root.get("phone"), "%" + user.getQuery() + "%"));
                } else {
                    return pre_and;
                }
                Predicate[] or = new Predicate[list_or.size()];
                Predicate pre_or = cb.or(list_or.toArray(or));
                return query.where(pre_and, pre_or).getRestriction();
            }
        }, pageable);
    }

    public Page<User> search(User user) {
        List<Department> departments = departmentDao.findAll();
        Page<User> userPage = findByList(user);
        for (User user1 : userPage.getContent()) {
            if (user1.getDepartmentId() != null) {
                for (Department department : departments) {
                    if (user1.getDepartmentId().equals(department.getId())) {
                        user1.setDepartmentId(department.getId());
                        user1.setDepartment(department.getName());
                    }
                }
            }
        }
        return userPage;
    }

    private void getDepartmentIds(String id, List<String> ids) {
        ids.add(id);
        List<Department> departments = departmentDao.findByParentId(id);
        if (departments.size() > 0) {
            for (Department department : departments) {
                getDepartmentIds(department.getId(), ids);
            }
        }
    }

    /**
     * 判断用户是否存在
     *
     * @param uid（可能是username,email,phone）
     */
    public boolean isExist(String uid) {
        User user = null;
        if (Regex.isEmail(uid)) {
            user = userDao.findByEmail(uid);
        } else if (Regex.isPhone(uid)) {
            user = userDao.findByPhone(uid);
        } else {
            user = userDao.findByUsername(uid);
        }
        return user != null;
    }



    /**
     * 注册用户
     *
     * @param user
     * @return
     */

    public User save(User user, List<MultipartFile> files) throws Exception {
        // 只是添加时限制
        if (org.apache.commons.lang3.StringUtils.isBlank(user.getId()) && StringUtils.isEmpty(user.getIsManage())) {
            // 添加用户数量限制 如果是政管，则查询政管下所有企业的所有用户(包括政管)，如果是企业那么就只需查企业下的用户
            Company company = companyDao.findById(user.getCompanyId());
            int userMax = customAppVersionDao.getCustomAppVersion(user.getCompanyId()).stream().map(CustomAppVersion::getMaxUser).reduce((a, b) -> a + b).get();
            if ("1".equals(company.getType())) {  // 企业
                // 获取该企业的所有用户
                int compAllUser = companyDao.getCompAllUser(user.getCompanyId());
                if (compAllUser >= userMax) {
                    throw new BusinessException("该企业用户数已达最大, 不能再新建。最多限制数量: " + userMax + ", 已创建的用户数量: " + compAllUser);
                }
            } else if ("2".equals(company.getType())) {    // 政管
                // 获取该政管及下辖企业的所有用户
                int allUser = companyDao.getAllUser(company.getId());
                if (allUser >= userMax) {
                    throw new BusinessException("该政管用户数已达最大, 不能再新建。最多限制数量: " + userMax + ", 已创建的用户数量: " + allUser);
                }
            }
        }
        Date datetime = new Date();
        if (!CollectionUtils.isEmpty(userDao.getByUsername(user.getUsername()))) {
            throw new UserException("E0003", "username用户名重复");
        }
//        if (userDao.findPhone(user.getPhone()) != null) {
//            throw new UserException("E0001");
//        }
        if (!StringUtils.isEmpty(user.getEmail()) && !CollectionUtils.isEmpty(userDao.getByEmail(user.getEmail()))) {
            throw new UserException("E0003");
        }
        if (!StringUtils.isEmpty(user.getPhone()) && !CollectionUtils.isEmpty(userDao.getByPhone(user.getPhone()))) {
            throw new UserException("E0002");
        }
        fileService.upload(null, user, files);
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(CryptUtil.md5(user.getPassword()));
        }
        user.setCreatetime(datetime);
        user.setUpdatetime(datetime);
        return userDao.save(user);
    }

    public User save2(User user) throws Exception {
        // 只是添加时限制
        if (org.apache.commons.lang3.StringUtils.isBlank(user.getId()) && StringUtils.isEmpty(user.getIsManage())) {
            // 添加用户数量限制 如果是政管，则查询政管下所有企业的所有用户(包括政管)，如果是企业那么就只需查企业下的用户
            Company company = companyDao.findById(user.getCompanyId());
            int userMax = customAppVersionDao.getCustomAppVersion(user.getCompanyId()).stream().map(CustomAppVersion::getMaxUser).reduce((a, b) -> a + b).get();
            if ("1".equals(company.getType())) {  // 企业
                // 获取该企业的所有用户
                int compAllUser = companyDao.getCompAllUser(user.getCompanyId());
                if (compAllUser >= userMax) {
                    throw new BusinessException("该企业用户数已达最大, 不能再新建。最多限制数量: " + userMax + ", 已创建的用户数量: " + compAllUser);
                }
            } else if ("2".equals(company.getType())) {    // 政管
                // 获取该政管及下辖企业的所有用户
                int allUser = companyDao.getAllUser(company.getId());
                if (allUser >= userMax) {
                    throw new BusinessException("该政管用户数已达最大, 不能再新建。最多限制数量: " + userMax + ", 已创建的用户数量: " + allUser);
                }
            }
        }
        Date datetime = new Date();
        if (!CollectionUtils.isEmpty(userDao.getByUsername(user.getUsername()))) {
            throw new UserException("username用户名重复");
        }
//        if (userDao.findPhone(user.getPhone()) != null) {
//            throw new UserException("E0001");
//        }
        if (!StringUtils.isEmpty(user.getEmail()) && !CollectionUtils.isEmpty(userDao.getByEmail(user.getEmail()))) {
            throw new UserException("E0003");
        }
        if (!StringUtils.isEmpty(user.getPhone()) && !CollectionUtils.isEmpty(userDao.getByPhone(user.getPhone()))) {
            throw new UserException("E0002");
        }
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(CryptUtil.md5(user.getPassword()));
        }
        user.setCreatetime(datetime);
        user.setUpdatetime(datetime);
        return userDao.save(user);
    }

    /**
     * 通过手机注册用户
     *
     * @param user
     * @return
     */
    public User registerByPhone(User user) {
        Date datetime = new Date();
        if (!StringUtils.isEmpty(user.getEmail()) && userDao.findByEmail(user.getEmail()) != null) {
            throw new UserException("E0003");
        }
        if (!StringUtils.isEmpty(user.getPhone()) && userDao.findByPhone(user.getPhone()) != null) {
            throw new UserException("E0002");
        }
        user.setCreatetime(datetime);
        user.setUpdatetime(datetime);
        return userDao.save(user);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    public User update(User user, List<MultipartFile> files) throws Exception {
        User oldUser = userDao.findById(user.getId());
        if (user.getUsername() != null && !user.getUsername().equals(oldUser.getUsername())) {
            if (userDao.findByUsername(user.getUsername()) != null) {
                throw new UserException("E0001");
            }
        }
        if (user.getEmail() != null && !user.getEmail().equals(oldUser.getEmail())) {
            if (userDao.findByEmail(user.getEmail()) != null) {
                throw new UserException("E0003");
            }
        }
        if (user.getPhone() != null && !user.getPhone().equals(oldUser.getPhone())) {
            if (userDao.findByPhone(user.getPhone()) != null) {
                throw new UserException("E0002");
            }
        }
        if (user.getPassword() != null && !user.getPassword().equals(oldUser.getPassword())) {
            user.setPassword(CryptUtil.md5(user.getPassword()));
        }
        fileService.upload(oldUser, user, files);
        return userDao.save(user);
    }

    public User update2(User user) throws Exception {
        User oldUser = userDao.findById(user.getId());
        if (user.getUsername() != null && !user.getUsername().equals(oldUser.getUsername())) {
            if (userDao.findByUsername(user.getUsername()) != null) {
                throw new UserException("E0001");
            }
        }
        if (user.getEmail() != null && !user.getEmail().equals(oldUser.getEmail())) {
            if (userDao.findByEmail(user.getEmail()) != null) {
                throw new UserException("E0003");
            }
        }
        if (user.getPhone() != null && !user.getPhone().equals(oldUser.getPhone())) {
            if (userDao.findByPhone(user.getPhone()) != null) {
                throw new UserException("E0002");
            }
        }
        if (user.getPassword() != null && !user.getPassword().equals(oldUser.getPassword())) {
            user.setPassword(CryptUtil.md5(user.getPassword()));
        }
        return userDao.save(user);
    }

    /**
     * 根据用户id绑定邮箱
     *
     * @param userId
     * @param email
     * @return
     */
    public boolean bindEmail(String userId, String email) {
        User userFinded = userDao.findByEmail(email);
        User persistent = userDao.findById(userId);
        if (userFinded != null && !userFinded.getId().equals(persistent.getId())) {
            throw new UserException("E0003");
        }
        persistent.setEmail(email);
        persistent.setUpdatetime(new Date());
        userDao.save(persistent);
        return true;
    }

    /**
     * 根据用户id绑定手机
     *
     * @param userId
     * @param phone
     * @return
     */
    public boolean bindPhone(String userId, String phone) {
        User userFinded = userDao.findByPhone(phone);
        User persistent = userDao.findById(userId);
        if (userFinded != null && !userFinded.getId().equals(persistent.getId())) {
            throw new UserException("E0002");
        }
        persistent.setPhone(phone);
        persistent.setUpdatetime(new Date());
        userDao.save(persistent);
        return true;
    }

    /**
     * 对用户进行上锁解锁
     *
     * @param userId
     * @param locked
     * @return
     */
    public boolean lockUser(String userId, boolean locked) {
        User persistent = userDao.findById(userId);
        persistent.setLocked(locked);
        userDao.save(persistent);
        return true;
    }

    /**
     * 加载user
     *
     * @param id
     * @return
     */
    public User findById(String id) {
        User user = userDao.findById(id);
        if (user == null) {
            throw new UserException("5000", "用户不存在");
        }
        user.setDepartment(departmentDao.getByName(user.getDepartmentId()));
        return user;
    }

    public Integer findCountByCompanyId(String companyId) {
        return userDao.userNum(companyId);
    }

    @Autowired
    private ColdUserDao coldUserDao;

    /**
     * 用户登录
     *
     * @param uid      可以是username,phone,email
     * @param password 密码
     * @param appid    应用id
     * @return
     */
    public JSONObject login(String uid, String password, String appid) {
        Optional<App> optional = appDao.findById(appid);
        if (!optional.isPresent()) {
            throw new UserException("E0007");
        }
        if (!optional.get().isUsed()) {
            throw new UserException("E0008");
        }
        User user = userDao.findByPhone(uid);
//        User user = userDao.findByUsername(uid);
//        if (Regex.isEmail(uid)) {
//            user = userDao.findByEmail(uid);
//        } else if (Regex.isPhone(uid)) {
//            user = userDao.findByPhone(uid);
//        } else {
//            user = userDao.findByUsername(uid);
//        }
        JSONObject result = new JSONObject();
        if (user == null) {
            // 兼容西昌的租户
            List<ColdUser> byPhone = coldUserDao.findByPhone(uid);
            if (CollectionUtils.isEmpty(byPhone))
                throw new UserException("E0005");
            ColdUser coldUser = byPhone.get(0);
            if (!coldUser.getPassword().equals(CryptUtil.md5(password))) {
                throw new UserException("E0006");
            }
            result.put("userInfo", coldUser);
            return result;
        }
        if (!user.getPassword().equals(CryptUtil.md5(password))) {
            throw new UserException("E0006");
        }
        if (user.isLocked()) {
            throw new UserException("E0004");
        }
//        if(!resourceService.hasApp(user.getId(), appid)){
//            throw new UserException("E0009");
//        }
        CompanyCustomAppVersion cs = new CompanyCustomAppVersion();
        cs.setCompanyId(user.getCompanyId());
        cs.setAppId(appid);

        List<AppMenuTree> appMenuTrees = null;
        Company company = companyDao.findById(user.getCompanyId()); // 这里存在问题 空指针
        if (company != null && company.getState() == 1) {
            throw new UserException("500", "该用户已被禁用，请联系管理员");
        }
        if (company != null) {
            if (company.getUserId().equals(user.getId())) { //如果账号是公司账号
                List<CompanyCustomAppVersion> companyCustomAppVersions = companyCustomAppVersionDao.findByCompanyId(company.getId());
                //如果已经绑定产品
                if (companyCustomAppVersions != null && companyCustomAppVersions.size() > 0) {
                    appMenuTrees = resourceService.findMenusByCompanyId(company.getId());
                } else {
                    // 解决 001 超管 查不出来权限
                    if (!StringUtils.isEmpty(user.getId())) {
                        appMenuTrees = resourceService.findMenusByUserId(user.getId());
                    } else if (!StringUtils.isEmpty(user.getDepartmentId())) {
                        appMenuTrees = resourceService.findMenusByDepartmentId(user.getDepartmentId());
                    }
                }
            } else {
                if (!StringUtils.isEmpty(user.getId())) {
                    // 有userId则跟据userId查询权限，没有则跟据部门ID查询
                    appMenuTrees = resourceService.findMenusByUserId(user.getId());
                } else if (!StringUtils.isEmpty(user.getDepartmentId())) {
                    appMenuTrees = resourceService.findMenusByDepartmentId(user.getDepartmentId());
                }
            }
        } else {
            // 不是公司账号，就去找个人权限    部门ID可能会出现空的情况
            if (!StringUtils.isEmpty(user.getId())) {
                appMenuTrees = resourceService.findMenusByUserId(user.getId());
            } else if (!StringUtils.isEmpty(user.getDepartmentId())) {
                appMenuTrees = resourceService.findMenusByDepartmentId(user.getDepartmentId());
            }
        }
        Department department = departmentDao.findById(user.getDepartmentId());
        if (department != null) {
            user.setDepartment(department.getName());
        }
        result.put("userInfo", user);
        result.put("company", company);
        for (AppMenuTree appMenuTree : appMenuTrees) {
            App app = appDao.findByName(appMenuTree.getAppName());
            if (app == null) {
                continue;
            }
            appMenuTree.setTibetName(app.getTibetName());
        }
        result.put("appMenus", appMenuTrees);
        return result;
    }

    public JSONObject loginV1(String id) {
        User user = userDao.findById(id);
        if (Objects.isNull(user)) {
            user = userDao.findByLoginId(id);
        }
        JSONObject result = new JSONObject();
        if (user.isLocked()) {
            throw new UserException("E0004");
        }
        List<AppMenuTree> appMenuTrees = null;
        Company company = companyDao.findById(user.getCompanyId()); // 这里存在问题 空指针
        if (company != null && company.getState() == 1) {
            throw new UserException("500", "该用户已被禁用，请联系管理员");
        }
        if (company != null) {
            if (company.getUserId().equals(user.getId())) { //如果账号是公司账号
                List<CompanyCustomAppVersion> companyCustomAppVersions = companyCustomAppVersionDao.findByCompanyId(company.getId());
                //如果已经绑定产品
                if (companyCustomAppVersions != null && companyCustomAppVersions.size() > 0) {
                    appMenuTrees = resourceService.findMenusByCompanyId(company.getId());
                } else {
                    // 解决 001 超管 查不出来权限
                    if (!StringUtils.isEmpty(user.getId())) {
                        appMenuTrees = resourceService.findMenusByUserId(user.getId());
                    } else if (!StringUtils.isEmpty(user.getDepartmentId())) {
                        appMenuTrees = resourceService.findMenusByDepartmentId(user.getDepartmentId());
                    }
                }
            } else {
                if (!StringUtils.isEmpty(user.getId())) {
                    // 有userId则跟据userId查询权限，没有则跟据部门ID查询
                    appMenuTrees = resourceService.findMenusByUserId(user.getId());
                } else if (!StringUtils.isEmpty(user.getDepartmentId())) {
                    appMenuTrees = resourceService.findMenusByDepartmentId(user.getDepartmentId());
                }
            }
        } else {
            // 不是公司账号，就去找个人权限    部门ID可能会出现空的情况
            if (!StringUtils.isEmpty(user.getId())) {
                appMenuTrees = resourceService.findMenusByUserId(user.getId());
            } else if (!StringUtils.isEmpty(user.getDepartmentId())) {
                appMenuTrees = resourceService.findMenusByDepartmentId(user.getDepartmentId());
            }
        }
        Department department = departmentDao.findById(user.getDepartmentId());
        if (department != null) {
            user.setDepartment(department.getName());
        }
        result.put("userInfo", user);
        for (AppMenuTree appMenuTree : appMenuTrees) {
            App app = appDao.findByName(appMenuTree.getAppName());
            if (app == null) {
                continue;
            }
            appMenuTree.setTibetName(app.getTibetName());
        }
        result.put("appMenus", appMenuTrees);
        return result;
    }

    /**
     * 用户登录
     *
     * @param uid      可以是username,phone,email
     * @param password 密码
     * @return
     */
    public JSONObject login(String uid, String password) {

        User user = null;
        if (Regex.isEmail(uid)) {
            user = userDao.findByEmail(uid);
        } else if (Regex.isPhone(uid)) {
            user = userDao.findByPhone(uid);
        } else {
            user = userDao.findByUsername(uid);
        }
        if (user == null) {
            throw new UserException("E0005");
        }
        if (!user.getPassword().equals(password)) {
            throw new UserException("E0006");
        }
        if (user.isLocked()) {
            throw new UserException("E0004");
        }
        List<AppMenuTree> appMenuTrees = resourceService.findMenusByUserId(user.getId());
        JSONObject result = new JSONObject();
        result.put("userInfo", user);
        result.put("appMenus", appMenuTrees);
        return result;
    }

    public List<User> findByAll(JSONObject param) {
        String companyId = param.getString("companyId");
        if (param.containsKey("name") && param.getString("name") != null) {
            String name = param.getString("name");
            return userDao.findByCompanyIdAndName(companyId, name);
        }
        return userDao.findByCompanyId(companyId);
    }

    public boolean checkPassword(JSONObject param) {
        String userId = param.getString("userId");
        String password = param.getString("password");
        User user = userDao.findById(userId);
        if (user == null) {
            throw new UserException("5000", "用户不存在");
        }
        if (user.getPassword() != null && user.getPassword().equals(CryptUtil.md5(password))) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * @param users
     * @return
     */
    public List<User> inquire(List<User> users, String companyId) {
        List<Department> departments = departmentDao.findByCompanyId(companyId);
        if (departments == null && departments.size() == 0) {
            throw new BusinessException("500", "部门为空");
        }
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            setDepartments(user, departments);

        }
        return users;
    }

    /**
     * 赋值部门id
     *
     * @param user
     * @param departments
     */
    private void setDepartments(User user, List<Department> departments) {
        if (StringUtils.isEmpty(user.getDepartment())) {
            return;
        }
        for (Department department : departments) {
            if (user.getDepartment().equals(department.getName())) {
                String id = department.getId();
                user.setDepartmentId(id);
            }
        }
//        if(StringUtils.isEmpty(user.getDepartmentId())){
//           throw new BusinessException("500","未找到匹配的部门");
//        }
    }


    /**
     * 重置密码
     *
     * @param userId
     * @param password 明文
     */
    public void resetPassword(String userId, String password) {
        User user = userDao.findById(userId);
        user.setPassword(CryptUtil.md5(password));
        userDao.save(user);
    }

    /**
     * 查询12个月新增的用户
     *
     * @return
     */
    public Object newUsers() {
        Date date = new Date();
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        Integer month = ca.get(Calendar.MONTH) + 1;
        Integer year = ca.get(Calendar.YEAR);
        String dateStr = year.toString() + "-" + month.toString() + "-01";
        List<Integer> arr = new ArrayList<>();
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);    //当前月
            List<User> byProfessionAndCreatetimeBetween1 = userDao.findByCreatetimeBetween(startDate, date);
            if (!StringUtils.isEmpty(byProfessionAndCreatetimeBetween1)) {
                arr.add(0, byProfessionAndCreatetimeBetween1.size());
            } else {
                arr.add(0, 0);
            }
            Calendar ca1 = Calendar.getInstance();
            ca1.setTime(startDate);
            for (int i = 1; i < 12; i++) {
                Date ca1Time = ca1.getTime();
                ca1.add(Calendar.MONTH, -1);
                List<User> byProfessionAndCreatetimeBetween = userDao.findByCreatetimeBetween(ca1.getTime(), ca1Time);
                if (byProfessionAndCreatetimeBetween.size() != 0) {
                    arr.add(i, byProfessionAndCreatetimeBetween1.size());
                } else {
                    arr.add(i, 0);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return arr;
    }

    /**
     * 查询累计用户
     *
     * @return
     */
    public Object cumUsers() {
        Date date = new Date();
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        String dateStr = "2021-01-01";//2021年开始
        List<Integer> arr = new ArrayList<>();
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
            List<User> byProfessionAndCreatetimeBetween1 = userDao.findByCreatetimeBetween(startDate, date);
            if (!StringUtils.isEmpty(byProfessionAndCreatetimeBetween1)) {
                arr.add(0, byProfessionAndCreatetimeBetween1.size());
            } else {
                arr.add(0, 0);
            }
            Calendar ca1 = Calendar.getInstance();
            ca1.setTime(startDate);
            for (int i = 1; i < 12; i++) {
                Date ca1Time = ca1.getTime();
                ca1.add(Calendar.MONTH, -1);
                List<User> byProfessionAndCreatetimeBetween = userDao.findByCreatetimeBetween(startDate, ca1Time);
                if (byProfessionAndCreatetimeBetween.size() != 0) {
                    arr.add(i, byProfessionAndCreatetimeBetween1.size());
                } else {
                    arr.add(i, 0);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return arr;
    }

    /**
     * 查询生产监管用户数量
     *
     * @param companyId
     * @return
     */
    public Object numUser(String companyId) {
        List<Company> byParentId = companyDao.findByParentId(companyId);
        Integer integer = 0;
        for (Company company : byParentId) {
            List<User> byCompanyId = userDao.findByCompanyId(company.getId());
            integer = integer + byCompanyId.size();
        }
        return integer;
    }

    public Object userNum(String companyId) {
        return userDao.userNum(companyId);
    }

    //查询公司
    public List<User> findByCompanyId(String companyId) {
        return userDao.findByCompanyId(companyId);
    }


    @Transient
    public Object insetUserAndCompany(JSONObject param) {
        JSONObject bankInfo = param.getJSONObject("bankInfo");
        //用户信息
        User user = new User();
        user.setName(bankInfo.getString("name"));
        user.setPassword("e10adc3949ba59abbe56e057f20f883e");       //密码默认：123456
        user.setPhone(bankInfo.getString("tel"));
        user.setUsername(bankInfo.getString("tel"));
        user.setCreatetime(new Date());
        user.setLocked(false);
        user.setUserType(User.UserType.COMPANY);
        User us = userDao.save(user);


        //企业信息
        Company company = new Company();
        company.setName(bankInfo.getString("name"));
        company.setPhone(bankInfo.getString("tel"));
        company.setCreatetime(String.valueOf(System.currentTimeMillis()));
        company.setExamined("1");
        company.setExpiretime("2125/05/20");
        company.setType("2");
        company.setState(0);
        company.setUserId(us.getId());
        Company company1 = companyDao.save(company);
        userDao.updateCompanyId(us.getId(), company1.getId());
        return company1.getId();
    }
}
